#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/7/7 14:49
# @Author  : fuchen'en
# @Description:

from flask import Flask
from flask_cors import CORS
import os
from . import db
from .api import generate_api


def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__,
                instance_relative_config=True,
                static_folder="../client/dist/static",
                template_folder="../client/dist/templates")
    app.config.from_mapping(
        DEBUG=True,
        JSON_AS_ASCII=False,
        SECRET_KEY='dev',
        DATABASE=os.path.join(app.instance_path, 'server.sqlite'),
    )

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # enable CORS
    CORS(app, resource={r'/api/*': {'origins': '*'}})

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    db.init_app(app)

    generate_api(app)

    return app
